package com.feng.store.service.impl;

import com.feng.store.entity.Address;
import com.feng.store.mapper.AddressMapper;
import com.feng.store.mapper.DistrictMapper;
import com.feng.store.service.IAddressService;
import com.feng.store.service.IDistrictService;
import com.feng.store.service.ex.AddressCountLimitException;
import com.feng.store.service.ex.InsertException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
/** 新增收获地址的实现类 */
@Service
public class AddressServiceImpl implements IAddressService {
    @Value("${user.address.max-count}")
    private Integer maxCount;
    @Autowired
    private AddressMapper addressMapper;
    //在添加用户收货地址的业务层依赖于districtservice业务层接口
    @Autowired
    private IDistrictService districtService;
    @Override
    public void addNewAddress(Address address, String username, Integer uid) {
      //调用收货地址统计的方法
        Integer integer = addressMapper.countByUid(uid);
        if(integer>=maxCount){
            throw new AddressCountLimitException("用户收获地址超出了上限！");
        }
        //对address数据进行补充：省市区
        String Provincename = districtService.getNameBycode(address.getProvinceCode());
        String CityName = districtService.getNameBycode(address.getCityCode());
        String Areaname = districtService.getNameBycode(address.getAreaCode());
        address.setAddress(Provincename);
        address.setCityName(CityName);
        address.setAreaName(Areaname);


        if(integer==0){
            address.setIsDefault(1);
        }
        address.setUid(uid);
        address.setModifiedTime(new Date());
        address.setModifiedUser(username);
        address.setCreatedTime(new Date());
        address.setCreatedUser(username);
        //插入收获地址的方法

        Integer rows = addressMapper.insertAddress(address);
        if(rows!=1){
            throw new InsertException("插入用户的收货地址产生未知的异常！");
        }
    }
}
